import React from 'react';
import styles from './index.less';
import { update } from '@/utils/immutableUtil';
import { getAccessToken, getRefreshToken } from 'abc-request';
import { history } from 'umi';
import { getSSOUrl } from '@/services/account/api';
import getMsgFn from './msg';
import store from 'local-store-pro';

export default class extends React.Component {
  iframeRef = React.createRef();

  state = {
    //宜搭域名
    yidaOrigin: 'https://ykuwud.aliwork.com',

    // iframe地址
    url: '',
    targetUrl: '',
  };

  componentDidMount = () => {
    window.addEventListener('message', this.iframeToPage);
    this.getUrl();
  };

  componentWillUnmount = () => {
    window.removeEventListener('message', this.iframeToPage);
    clearInterval(this.resetTime);
  };

  //获取链接
  getUrl = async () => {
    var query = history.location.query;
    try {
      var rs = await getSSOUrl(
        {},
        {
          headers: {
            'App-Code': query.appCode,
            // 'App-Code': 'sop',
            'Channel-Code': 'portal-pc',
          },
        },
      );
      // var rs = {
      //   "data": {
      //     iframeUrl: "https://ykuwud.aliwork.com/o/benchuTest",
      //     targetUrl: "https://ykuwud.aliwork.com/o/benchuTest",
      //   },
      //   "code": 0,
      //   "message": "success",
      //   "requestId": null,
      //   "success": true
      // }
      if (rs.success) {
        this.setState({
          url: rs.data.iframeUrl,
          targetUrl: rs.data.targetUrl,
        });
      }
    } catch (error) {}
  };

  // iframe 加载成功
  load = () => {
    //这块由于 iframe 内部重定向 load函数时机不对
    this.time = setInterval(() => {
      this.sendToken('userTokenInfo');
      this.setTimeToken();
    }, 300);
  };

  //传递token
  sendToken = type => {
    var loginInfo = store('loginInfo') || {};
    console.log(loginInfo);

    var accessToken = (this.accessToken = getAccessToken());
    var refreshToken = (this.refreshToken = getRefreshToken());

    var obj = {
      type: type,
      data: {
        ...loginInfo,
        accessToken: accessToken,
        refreshToken: refreshToken,
        parentOrigin: window.location.origin,
      },
    };
    this.sendMsgToIframe(obj);
  };

  //定时器刷token
  setTimeToken = () => {
    this.resetTime = setInterval(() => {
      var accessToken = getAccessToken();
      //token有变化
      if (this.accessToken != accessToken) {
        this.sendToken('resetToken');
      }
    }, 1000);
  };

  //我向 iframe 发送数据
  sendMsgToIframe = (obj = {}) => {
    if (!this.iframeRef.current) {
      return;
    }
    var url = this.state.targetUrl;
    this.iframeRef.current.contentWindow.postMessage(JSON.stringify(obj), url);
  };

  // iframe 向我 发送数据
  iframeToPage = event => {
    // 确保消息来源的安全性
    if (event.origin != this.state.yidaOrigin) return;
    if (typeof event.data != 'string') return;
    var data = JSON.parse(event.data);

    //初始化完成
    if (data.type == 'childInit') {
      console.log('childInit ');
      clearInterval(this.time);
      return;
    }

    var func = getMsgFn(data.type);
    func(data, this);
  };

  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);
  render() {
    const { url } = this.state;
    return (
      <div className={styles.container}>
        {url && (
          <iframe
            ref={this.iframeRef}
            src={url}
            className={styles.iframe}
            onLoad={() => {
              this.load();
            }}
          />
        )}
      </div>
    );
  }
}
